// SPDX-FileCopyrightText: 2025 UnionTech Software Technology Co., Ltd.
// SPDX-License-Identifier: MIT

package metrics

import (
	"context"
	"strconv"
	"sync"
	"sync/atomic"
	"time"

	"github.com/prometheus/client_golang/prometheus"

	"uos_uwsgi_exporter/internal/config"
	"uos_uwsgi_exporter/pkg/errors"
	"uos_uwsgi_exporter/pkg/logger"
)

// Collector uWSGI指标收集器
type Collector struct {
	config *config.Config
	mu     sync.RWMutex
	logger logger.Logger

	// 性能监控状态
	activeCollections int64 // 当前活跃的收集任务数

	// 基础指标
	listenQueue       *prometheus.Desc
	listenQueueErrors *prometheus.Desc
	signalQueue       *prometheus.Desc
	load              *prometheus.Desc
	pid               *prometheus.Desc
	uid               *prometheus.Desc
	gid               *prometheus.Desc
	cores             *prometheus.Desc
	versionInfo       *prometheus.Desc // 新增：uWSGI版本信息

	// Worker指标
	workerRequests      *prometheus.Desc
	workerExceptions    *prometheus.Desc
	workerStatus        *prometheus.Desc
	workerPID           *prometheus.Desc // 新增：Worker进程PID
	workerCheap         *prometheus.Desc // 新增：Cheap模式状态
	workerBusy          *prometheus.Desc // 新增：忙碌状态
	workerAccepting     *prometheus.Desc // 新增：接受请求状态
	workerRSS           *prometheus.Desc
	workerVSZ           *prometheus.Desc
	workerRunningTime   *prometheus.Desc
	workerLastSpawn     *prometheus.Desc
	workerRespawnCount  *prometheus.Desc
	workerHarakiriCount *prometheus.Desc
	workerSignals       *prometheus.Desc
	workerSignalQueue   *prometheus.Desc
	workerDeltaRequests *prometheus.Desc
	workerWeight        *prometheus.Desc
	workerAvgRt         *prometheus.Desc
	workerTx            *prometheus.Desc
	workerRx            *prometheus.Desc
	workerQlen          *prometheus.Desc
	workerQlenErrors    *prometheus.Desc
	workerQlenMax       *prometheus.Desc
	workerQlenMaxErrors *prometheus.Desc

	// 应用指标
	appRequests    *prometheus.Desc
	appExceptions  *prometheus.Desc
	appStartupTime *prometheus.Desc
	appMasterPID   *prometheus.Desc
	appWorkerPID   *prometheus.Desc
	appModifier1   *prometheus.Desc // 新增：应用修饰符1
	appInfo        *prometheus.Desc // 新增：应用环境信息

	// 缓存指标
	cacheKeys   *prometheus.Desc
	cacheHits   *prometheus.Desc
	cacheMisses *prometheus.Desc

	// 锁指标
	locksCount *prometheus.Desc

	// 连接指标
	connectionErrors  *prometheus.Desc
	connectionTimeout *prometheus.Desc

	// 性能监控指标
	collectionDuration    *prometheus.Desc
	collectionErrors      *prometheus.Desc
	lastCollectionTime    *prometheus.Desc
	concurrentCollections *prometheus.Desc
	collectionTimeouts    *prometheus.Desc
}

// NewCollector 创建新的收集器
func NewCollector(cfg *config.Config) *Collector {
	return &Collector{
		config: cfg,
		logger: logger.DefaultLogger.WithField("component", "collector"),
		// 基础指标
		listenQueue: prometheus.NewDesc(
			"uwsgi_listen_queue",
			"uWSGI监听队列长度",
			[]string{"socket"}, nil,
		),
		listenQueueErrors: prometheus.NewDesc(
			"uwsgi_listen_queue_errors",
			"uWSGI监听队列错误数",
			[]string{"socket"}, nil,
		),
		signalQueue: prometheus.NewDesc(
			"uwsgi_signal_queue",
			"uWSGI信号队列长度",
			[]string{"socket"}, nil,
		),
		load: prometheus.NewDesc(
			"uwsgi_load",
			"uWSGI负载",
			[]string{"socket"}, nil,
		),
		pid: prometheus.NewDesc(
			"uwsgi_pid",
			"uWSGI主进程PID",
			[]string{"socket"}, nil,
		),
		uid: prometheus.NewDesc(
			"uwsgi_uid",
			"uWSGI进程UID",
			[]string{"socket"}, nil,
		),
		gid: prometheus.NewDesc(
			"uwsgi_gid",
			"uWSGI进程GID",
			[]string{"socket"}, nil,
		),
		cores: prometheus.NewDesc(
			"uwsgi_cores",
			"uWSGI核心数",
			[]string{"socket"}, nil,
		),
		versionInfo: prometheus.NewDesc(
			"uwsgi_version_info",
			"uWSGI版本信息",
			[]string{"socket", "version"}, nil,
		),

		// Worker指标
		workerRequests: prometheus.NewDesc(
			"uwsgi_worker_requests",
			"Worker处理的请求数",
			[]string{"socket", "worker_id"}, nil,
		),
		workerExceptions: prometheus.NewDesc(
			"uwsgi_worker_exceptions",
			"Worker异常数",
			[]string{"socket", "worker_id"}, nil,
		),
		workerStatus: prometheus.NewDesc(
			"uwsgi_worker_status",
			"Worker状态 (1=运行中, 0=停止)",
			[]string{"socket", "worker_id"}, nil,
		),
		workerPID: prometheus.NewDesc(
			"uwsgi_worker_pid",
			"Worker进程PID",
			[]string{"socket", "worker_id"}, nil,
		),
		workerCheap: prometheus.NewDesc(
			"uwsgi_worker_cheap",
			"Worker Cheap模式状态 (1=启用, 0=禁用)",
			[]string{"socket", "worker_id"}, nil,
		),
		workerBusy: prometheus.NewDesc(
			"uwsgi_worker_busy",
			"Worker忙碌状态 (1=忙碌, 0=空闲)",
			[]string{"socket", "worker_id"}, nil,
		),
		workerAccepting: prometheus.NewDesc(
			"uwsgi_worker_accepting",
			"Worker接受请求状态 (1=接受, 0=不接受)",
			[]string{"socket", "worker_id"}, nil,
		),
		workerRSS: prometheus.NewDesc(
			"uwsgi_worker_rss",
			"Worker RSS内存使用量(KB)",
			[]string{"socket", "worker_id"}, nil,
		),
		workerVSZ: prometheus.NewDesc(
			"uwsgi_worker_vsz",
			"Worker VSZ内存使用量(KB)",
			[]string{"socket", "worker_id"}, nil,
		),
		workerRunningTime: prometheus.NewDesc(
			"uwsgi_worker_running_time",
			"Worker运行时间(秒)",
			[]string{"socket", "worker_id"}, nil,
		),
		workerLastSpawn: prometheus.NewDesc(
			"uwsgi_worker_last_spawn",
			"Worker最后启动时间(Unix时间戳)",
			[]string{"socket", "worker_id"}, nil,
		),
		workerRespawnCount: prometheus.NewDesc(
			"uwsgi_worker_respawn_count",
			"Worker重启次数",
			[]string{"socket", "worker_id"}, nil,
		),
		workerHarakiriCount: prometheus.NewDesc(
			"uwsgi_worker_harakiri_count",
			"Worker超时终止次数",
			[]string{"socket", "worker_id"}, nil,
		),
		workerSignals: prometheus.NewDesc(
			"uwsgi_worker_signals",
			"Worker信号数",
			[]string{"socket", "worker_id"}, nil,
		),
		workerSignalQueue: prometheus.NewDesc(
			"uwsgi_worker_signal_queue",
			"Worker信号队列长度",
			[]string{"socket", "worker_id"}, nil,
		),
		workerDeltaRequests: prometheus.NewDesc(
			"uwsgi_worker_delta_requests",
			"Worker增量请求数",
			[]string{"socket", "worker_id"}, nil,
		),
		workerWeight: prometheus.NewDesc(
			"uwsgi_worker_weight",
			"Worker权重",
			[]string{"socket", "worker_id"}, nil,
		),
		workerAvgRt: prometheus.NewDesc(
			"uwsgi_worker_avg_rt",
			"Worker平均响应时间(毫秒)",
			[]string{"socket", "worker_id"}, nil,
		),
		workerTx: prometheus.NewDesc(
			"uwsgi_worker_tx",
			"Worker发送字节数",
			[]string{"socket", "worker_id"}, nil,
		),
		workerRx: prometheus.NewDesc(
			"uwsgi_worker_rx",
			"Worker接收字节数",
			[]string{"socket", "worker_id"}, nil,
		),
		workerQlen: prometheus.NewDesc(
			"uwsgi_worker_qlen",
			"Worker队列长度",
			[]string{"socket", "worker_id"}, nil,
		),
		workerQlenErrors: prometheus.NewDesc(
			"uwsgi_worker_qlen_errors",
			"Worker队列错误数",
			[]string{"socket", "worker_id"}, nil,
		),
		workerQlenMax: prometheus.NewDesc(
			"uwsgi_worker_qlen_max",
			"Worker最大队列长度",
			[]string{"socket", "worker_id"}, nil,
		),
		workerQlenMaxErrors: prometheus.NewDesc(
			"uwsgi_worker_qlen_max_errors",
			"Worker最大队列错误数",
			[]string{"socket", "worker_id"}, nil,
		),

		// 应用指标
		appRequests: prometheus.NewDesc(
			"uwsgi_app_requests",
			"应用处理的请求数",
			[]string{"socket", "app_id", "mount_point"}, nil,
		),
		appExceptions: prometheus.NewDesc(
			"uwsgi_app_exceptions",
			"应用异常数",
			[]string{"socket", "app_id", "mount_point"}, nil,
		),
		appStartupTime: prometheus.NewDesc(
			"uwsgi_app_startup_time",
			"应用启动时间(Unix时间戳)",
			[]string{"socket", "app_id", "mount_point"}, nil,
		),
		appMasterPID: prometheus.NewDesc(
			"uwsgi_app_master_pid",
			"应用主进程PID",
			[]string{"socket", "app_id", "mount_point"}, nil,
		),
		appWorkerPID: prometheus.NewDesc(
			"uwsgi_app_worker_pid",
			"应用Worker进程PID",
			[]string{"socket", "app_id", "mount_point"}, nil,
		),
		appModifier1: prometheus.NewDesc(
			"uwsgi_app_modifier1",
			"应用修饰符1",
			[]string{"socket", "app_id", "mount_point"}, nil,
		),
		appInfo: prometheus.NewDesc(
			"uwsgi_app_info",
			"应用环境信息",
			[]string{"socket", "app_id", "mount_point", "python_version", "virtualenv", "script"}, nil,
		),

		// 缓存指标
		cacheKeys: prometheus.NewDesc(
			"uwsgi_cache_keys",
			"缓存键数量",
			[]string{"socket", "cache_name"}, nil,
		),
		cacheHits: prometheus.NewDesc(
			"uwsgi_cache_hits",
			"缓存命中数",
			[]string{"socket", "cache_name"}, nil,
		),
		cacheMisses: prometheus.NewDesc(
			"uwsgi_cache_misses",
			"缓存未命中数",
			[]string{"socket", "cache_name"}, nil,
		),

		// 锁指标
		locksCount: prometheus.NewDesc(
			"uwsgi_locks_count",
			"锁数量",
			[]string{"socket", "lock_name"}, nil,
		),

		// 连接指标
		connectionErrors: prometheus.NewDesc(
			"uwsgi_connection_errors",
			"连接错误数",
			[]string{"socket"}, nil,
		),
		connectionTimeout: prometheus.NewDesc(
			"uwsgi_connection_timeout",
			"连接超时数",
			[]string{"socket"}, nil,
		),

		// 性能监控指标
		collectionDuration: prometheus.NewDesc(
			"uwsgi_exporter_collection_duration_seconds",
			"指标收集耗时(秒)",
			[]string{"socket", "status"}, nil,
		),
		collectionErrors: prometheus.NewDesc(
			"uwsgi_exporter_collection_errors_total",
			"指标收集错误总数",
			[]string{"socket", "error_type"}, nil,
		),
		lastCollectionTime: prometheus.NewDesc(
			"uwsgi_exporter_last_collection_timestamp_seconds",
			"最后一次成功收集的时间戳",
			[]string{"socket"}, nil,
		),
		concurrentCollections: prometheus.NewDesc(
			"uwsgi_exporter_concurrent_collections",
			"当前并发收集数",
			[]string{}, nil,
		),
		collectionTimeouts: prometheus.NewDesc(
			"uwsgi_exporter_collection_timeouts_total",
			"收集超时总数",
			[]string{"socket"}, nil,
		),
	}
}

// Describe 实现prometheus.Collector接口
func (c *Collector) Describe(ch chan<- *prometheus.Desc) {
	// 基础指标
	ch <- c.listenQueue
	ch <- c.listenQueueErrors
	ch <- c.signalQueue
	ch <- c.load
	ch <- c.pid
	ch <- c.uid
	ch <- c.gid
	ch <- c.cores
	ch <- c.versionInfo

	// Worker指标
	ch <- c.workerRequests
	ch <- c.workerExceptions
	ch <- c.workerStatus
	ch <- c.workerPID
	ch <- c.workerCheap
	ch <- c.workerBusy
	ch <- c.workerAccepting
	ch <- c.workerRSS
	ch <- c.workerVSZ
	ch <- c.workerRunningTime
	ch <- c.workerLastSpawn
	ch <- c.workerRespawnCount
	ch <- c.workerHarakiriCount
	ch <- c.workerSignals
	ch <- c.workerSignalQueue
	ch <- c.workerDeltaRequests
	ch <- c.workerWeight
	ch <- c.workerAvgRt
	ch <- c.workerTx
	ch <- c.workerRx
	ch <- c.workerQlen
	ch <- c.workerQlenErrors
	ch <- c.workerQlenMax
	ch <- c.workerQlenMaxErrors

	// 应用指标
	ch <- c.appRequests
	ch <- c.appExceptions
	ch <- c.appStartupTime
	ch <- c.appMasterPID
	ch <- c.appWorkerPID
	ch <- c.appModifier1
	ch <- c.appInfo

	// 缓存指标
	ch <- c.cacheKeys
	ch <- c.cacheHits
	ch <- c.cacheMisses

	// 锁指标
	ch <- c.locksCount

	// 连接指标
	ch <- c.connectionErrors
	ch <- c.connectionTimeout

	// 性能监控指标
	ch <- c.collectionDuration
	ch <- c.collectionErrors
	ch <- c.lastCollectionTime
	ch <- c.concurrentCollections
	ch <- c.collectionTimeouts
}

// safeMetricSend 安全地向 channel 发送指标，避免向已关闭的 channel 发送数据
func (c *Collector) safeMetricSend(ch chan<- prometheus.Metric, metric prometheus.Metric) {
	defer func() {
		if r := recover(); r != nil {
			// 捕获 panic，记录日志但不中断程序
			c.logger.WithField("error", r).Debug("Failed to send metric to channel (channel may be closed)")
		}
	}()

	select {
	case ch <- metric:
		// 成功发送
	default:
		// Channel 已满或已关闭，跳过
		c.logger.Debug("Channel full or closed, skipping metric")
	}
}

// Collect 实现prometheus.Collector接口
func (c *Collector) Collect(ch chan<- prometheus.Metric) {
	collectionStart := time.Now()

	c.mu.RLock()
	defer c.mu.RUnlock()

	// 创建上下文，设置整体收集超时
	ctx, cancel := context.WithTimeout(context.Background(), c.config.CollectionTimeout)
	defer cancel()

	// 使用 WaitGroup 等待所有 goroutine 完成
	var wg sync.WaitGroup

	// 创建带缓冲的信号量控制并发数
	semaphore := make(chan struct{}, c.config.MaxConcurrency)

	// 统计变量
	var successCount, errorCount, timeoutCount int64

	// 并发收集所有socket的指标
	for _, socket := range c.config.Sockets {
		wg.Add(1)
		go func(socket string) {
			defer wg.Done()

			// 获取信号量，控制并发数
			select {
			case semaphore <- struct{}{}:
				defer func() { <-semaphore }()
			case <-ctx.Done():
				c.logger.WithField("socket", socket).Warn("Collection timeout reached, skipping socket")
				atomic.AddInt64(&timeoutCount, 1)
				// 安全地记录超时指标
				c.safeMetricSend(ch, prometheus.MustNewConstMetric(
					c.collectionTimeouts,
					prometheus.CounterValue,
					1.0,
					socket,
				))
				return
			}

			// 增加活跃收集计数
			atomic.AddInt64(&c.activeCollections, 1)
			defer atomic.AddInt64(&c.activeCollections, -1)

			// 在超时上下文中收集指标
			success := c.collectSocketMetricsWithContext(ctx, socket, ch)
			if success {
				atomic.AddInt64(&successCount, 1)
			} else {
				atomic.AddInt64(&errorCount, 1)
			}
		}(socket)
	}

	// 记录当前并发收集数
	currentConcurrent := atomic.LoadInt64(&c.activeCollections)
	ch <- prometheus.MustNewConstMetric(
		c.concurrentCollections,
		prometheus.GaugeValue,
		float64(currentConcurrent),
	)

	// 等待所有收集任务完成或超时
	done := make(chan struct{})
	go func() {
		wg.Wait()
		close(done)
	}()

	select {
	case <-done:
		// 所有任务正常完成
		totalDuration := time.Since(collectionStart).Seconds()
		c.logger.WithFields(map[string]interface{}{
			"duration":      time.Since(collectionStart),
			"success":       successCount,
			"errors":        errorCount,
			"timeouts":      timeoutCount,
			"total_sockets": len(c.config.Sockets),
		}).Info("Collection completed successfully")

		// 记录整体收集性能指标
		ch <- prometheus.MustNewConstMetric(
			c.collectionDuration,
			prometheus.GaugeValue,
			totalDuration,
			"all", "success",
		)

	case <-ctx.Done():
		// 超时或取消
		totalDuration := time.Since(collectionStart).Seconds()
		c.logger.WithFields(map[string]interface{}{
			"duration": time.Since(collectionStart),
			"error":    ctx.Err().Error(),
		}).Error("Collection context cancelled")

		// 记录超时的收集性能指标
		ch <- prometheus.MustNewConstMetric(
			c.collectionDuration,
			prometheus.GaugeValue,
			totalDuration,
			"all", "timeout",
		)
	}
}

// collectSocketMetricsWithContext 在上下文中收集单个socket的指标
func (c *Collector) collectSocketMetricsWithContext(ctx context.Context, socket string, ch chan<- prometheus.Metric) bool {
	// 检查上下文是否已取消
	select {
	case <-ctx.Done():
		c.logger.WithField("socket", socket).Debug("Context cancelled before collecting metrics")
		return false
	default:
	}

	start := time.Now()
	var success bool
	var errorType string

	defer func() {
		duration := time.Since(start).Seconds()
		status := "success"
		if !success {
			status = "error"
		}

		// 记录单个socket的收集性能
		ch <- prometheus.MustNewConstMetric(
			c.collectionDuration,
			prometheus.GaugeValue,
			duration,
			socket, status,
		)

		if success {
			// 记录最后成功收集时间
			ch <- prometheus.MustNewConstMetric(
				c.lastCollectionTime,
				prometheus.GaugeValue,
				float64(time.Now().Unix()),
				socket,
			)
			c.logger.WithFields(map[string]interface{}{
				"socket":   socket,
				"duration": time.Since(start),
			}).Debug("Successfully collected metrics for socket")
		} else {
			// 记录错误
			ch <- prometheus.MustNewConstMetric(
				c.collectionErrors,
				prometheus.CounterValue,
				1.0,
				socket, errorType,
			)
			c.logger.WithFields(map[string]interface{}{
				"socket":     socket,
				"duration":   time.Since(start),
				"error_type": errorType,
			}).Warn("Failed to collect metrics for socket")
		}
	}()

	// 获取socket类型
	socketType := c.getSocketType(socket)

	// 创建uWSGI客户端，使用配置的超时时间
	client := NewuWSGIClient(socket, socketType, c.config.SocketTimeout)

	// 获取统计信息
	stats, err := client.GetStats()
	if err != nil {
		// 使用结构化错误处理
		if errors.IsTimeoutError(err) {
			errorType = "timeout"
		} else if errors.IsConnectionError(err) {
			errorType = "connection"
		} else {
			errorType = "unknown"
		}

		// 使用结构化日志记录错误
		logEntry := c.logger.WithError(err).WithFields(map[string]interface{}{
			"socket":     socket,
			"error_type": errorType,
			"component":  "collector",
		})

		// 根据错误严重程度选择日志级别
		severity := errors.GetSeverity(err)
		switch severity {
		case errors.SeverityCritical, errors.SeverityHigh:
			logEntry.Error("Failed to collect metrics from socket")
		case errors.SeverityMedium:
			logEntry.Warn("Failed to collect metrics from socket")
		case errors.SeverityLow:
			logEntry.Info("Failed to collect metrics from socket")
		}

		// 记录连接错误
		ch <- prometheus.MustNewConstMetric(
			c.connectionErrors,
			prometheus.CounterValue,
			1.0,
			socket,
		)
		return false
	}

	// 检查上下文是否已取消
	select {
	case <-ctx.Done():
		c.logger.WithField("socket", socket).Debug("Context cancelled while collecting metrics")
		errorType = "cancelled"
		return false
	default:
	}

	// 收集各类指标
	c.collectBasicMetrics(stats, socket, ch)
	c.collectWorkerMetrics(stats, socket, ch)
	c.collectAppMetrics(stats, socket, ch)
	c.collectCacheMetrics(stats, socket, ch)
	c.collectLockMetrics(stats, socket, ch)

	success = true
	return true
}

// collectSocketMetrics 收集单个socket的指标（保留向后兼容性）
func (c *Collector) collectSocketMetrics(socket string, ch chan<- prometheus.Metric) {
	ctx := context.Background()
	c.collectSocketMetricsWithContext(ctx, socket, ch)
}

// collectBasicMetrics 收集基础指标
func (c *Collector) collectBasicMetrics(stats *uWSGIStats, socket string, ch chan<- prometheus.Metric) {
	ch <- prometheus.MustNewConstMetric(
		c.listenQueue,
		prometheus.GaugeValue,
		float64(stats.ListenQueue),
		socket,
	)

	ch <- prometheus.MustNewConstMetric(
		c.listenQueueErrors,
		prometheus.CounterValue,
		float64(stats.ListenQueueErrors),
		socket,
	)

	ch <- prometheus.MustNewConstMetric(
		c.signalQueue,
		prometheus.GaugeValue,
		float64(stats.SignalQueue),
		socket,
	)

	ch <- prometheus.MustNewConstMetric(
		c.load,
		prometheus.GaugeValue,
		float64(stats.Load),
		socket,
	)

	ch <- prometheus.MustNewConstMetric(
		c.pid,
		prometheus.GaugeValue,
		float64(stats.PID),
		socket,
	)

	ch <- prometheus.MustNewConstMetric(
		c.uid,
		prometheus.GaugeValue,
		float64(stats.UID),
		socket,
	)

	ch <- prometheus.MustNewConstMetric(
		c.gid,
		prometheus.GaugeValue,
		float64(stats.GID),
		socket,
	)

	ch <- prometheus.MustNewConstMetric(
		c.cores,
		prometheus.GaugeValue,
		float64(stats.Cores),
		socket,
	)

	// 版本信息 (Info类型指标，值固定为1)
	ch <- prometheus.MustNewConstMetric(
		c.versionInfo,
		prometheus.GaugeValue,
		1.0,
		socket, stats.Version,
	)
}

// collectWorkerMetrics 收集Worker指标
func (c *Collector) collectWorkerMetrics(stats *uWSGIStats, socket string, ch chan<- prometheus.Metric) {
	for _, worker := range stats.Workers {
		workerID := strconv.Itoa(worker.ID)

		ch <- prometheus.MustNewConstMetric(
			c.workerRequests,
			prometheus.CounterValue,
			float64(worker.Requests),
			socket, workerID,
		)

		ch <- prometheus.MustNewConstMetric(
			c.workerExceptions,
			prometheus.CounterValue,
			float64(worker.Exceptions),
			socket, workerID,
		)

		// Worker状态：1=运行中, 0=停止
		status := 0.0
		if worker.Status == "idle" || worker.Status == "busy" {
			status = 1.0
		}
		ch <- prometheus.MustNewConstMetric(
			c.workerStatus,
			prometheus.GaugeValue,
			status,
			socket, workerID,
		)

		// Worker PID
		ch <- prometheus.MustNewConstMetric(
			c.workerPID,
			prometheus.GaugeValue,
			float64(worker.PID),
			socket, workerID,
		)

		// Worker Cheap模式状态
		ch <- prometheus.MustNewConstMetric(
			c.workerCheap,
			prometheus.GaugeValue,
			float64(worker.Cheap),
			socket, workerID,
		)

		// Worker忙碌状态
		ch <- prometheus.MustNewConstMetric(
			c.workerBusy,
			prometheus.GaugeValue,
			float64(worker.Busy),
			socket, workerID,
		)

		// Worker接受请求状态
		ch <- prometheus.MustNewConstMetric(
			c.workerAccepting,
			prometheus.GaugeValue,
			float64(worker.Accepting),
			socket, workerID,
		)

		ch <- prometheus.MustNewConstMetric(
			c.workerRSS,
			prometheus.GaugeValue,
			float64(worker.RSS),
			socket, workerID,
		)

		ch <- prometheus.MustNewConstMetric(
			c.workerVSZ,
			prometheus.GaugeValue,
			float64(worker.VSZ),
			socket, workerID,
		)

		ch <- prometheus.MustNewConstMetric(
			c.workerRunningTime,
			prometheus.GaugeValue,
			float64(worker.RunningTime),
			socket, workerID,
		)

		ch <- prometheus.MustNewConstMetric(
			c.workerLastSpawn,
			prometheus.GaugeValue,
			float64(worker.LastSpawn),
			socket, workerID,
		)

		ch <- prometheus.MustNewConstMetric(
			c.workerRespawnCount,
			prometheus.CounterValue,
			float64(worker.RespawnCount),
			socket, workerID,
		)

		ch <- prometheus.MustNewConstMetric(
			c.workerHarakiriCount,
			prometheus.CounterValue,
			float64(worker.HarakiriCount),
			socket, workerID,
		)

		ch <- prometheus.MustNewConstMetric(
			c.workerSignals,
			prometheus.CounterValue,
			float64(worker.Signals),
			socket, workerID,
		)

		ch <- prometheus.MustNewConstMetric(
			c.workerSignalQueue,
			prometheus.GaugeValue,
			float64(worker.SignalQueue),
			socket, workerID,
		)

		ch <- prometheus.MustNewConstMetric(
			c.workerDeltaRequests,
			prometheus.CounterValue,
			float64(worker.DeltaRequests),
			socket, workerID,
		)

		ch <- prometheus.MustNewConstMetric(
			c.workerWeight,
			prometheus.GaugeValue,
			float64(worker.Weight),
			socket, workerID,
		)

		ch <- prometheus.MustNewConstMetric(
			c.workerAvgRt,
			prometheus.GaugeValue,
			float64(worker.AvgRt),
			socket, workerID,
		)

		ch <- prometheus.MustNewConstMetric(
			c.workerTx,
			prometheus.CounterValue,
			float64(worker.Tx),
			socket, workerID,
		)

		ch <- prometheus.MustNewConstMetric(
			c.workerRx,
			prometheus.CounterValue,
			float64(worker.Rx),
			socket, workerID,
		)

		ch <- prometheus.MustNewConstMetric(
			c.workerQlen,
			prometheus.GaugeValue,
			float64(worker.Qlen),
			socket, workerID,
		)

		ch <- prometheus.MustNewConstMetric(
			c.workerQlenErrors,
			prometheus.CounterValue,
			float64(worker.QlenErrors),
			socket, workerID,
		)

		ch <- prometheus.MustNewConstMetric(
			c.workerQlenMax,
			prometheus.GaugeValue,
			float64(worker.QlenMax),
			socket, workerID,
		)

		ch <- prometheus.MustNewConstMetric(
			c.workerQlenMaxErrors,
			prometheus.CounterValue,
			float64(worker.QlenMaxErrors),
			socket, workerID,
		)
	}
}

// collectAppMetrics 收集应用指标
func (c *Collector) collectAppMetrics(stats *uWSGIStats, socket string, ch chan<- prometheus.Metric) {
	for _, app := range stats.Apps {
		appID := strconv.Itoa(app.ID)
		mountPoint := app.MountPoint
		if mountPoint == "" {
			mountPoint = "default"
		}

		ch <- prometheus.MustNewConstMetric(
			c.appRequests,
			prometheus.CounterValue,
			float64(app.Requests),
			socket, appID, mountPoint,
		)

		ch <- prometheus.MustNewConstMetric(
			c.appExceptions,
			prometheus.CounterValue,
			float64(app.Exceptions),
			socket, appID, mountPoint,
		)

		ch <- prometheus.MustNewConstMetric(
			c.appStartupTime,
			prometheus.GaugeValue,
			float64(app.StartupTime),
			socket, appID, mountPoint,
		)

		ch <- prometheus.MustNewConstMetric(
			c.appMasterPID,
			prometheus.GaugeValue,
			float64(app.MasterPID),
			socket, appID, mountPoint,
		)

		ch <- prometheus.MustNewConstMetric(
			c.appWorkerPID,
			prometheus.GaugeValue,
			float64(app.WorkerPID),
			socket, appID, mountPoint,
		)

		// 应用修饰符1
		ch <- prometheus.MustNewConstMetric(
			c.appModifier1,
			prometheus.GaugeValue,
			float64(app.Modifier1),
			socket, appID, mountPoint,
		)

		// 应用环境信息 (Info类型指标，值固定为1)
		pythonVersion := app.PythonVersion
		if pythonVersion == "" {
			pythonVersion = "unknown"
		}
		virtualenv := app.Virtualenv
		if virtualenv == "" {
			virtualenv = "none"
		}
		script := app.Script
		if script == "" {
			script = "unknown"
		}
		ch <- prometheus.MustNewConstMetric(
			c.appInfo,
			prometheus.GaugeValue,
			1.0,
			socket, appID, mountPoint, pythonVersion, virtualenv, script,
		)
	}
}

// collectCacheMetrics 收集缓存指标
func (c *Collector) collectCacheMetrics(stats *uWSGIStats, socket string, ch chan<- prometheus.Metric) {
	for cacheName, cacheData := range stats.Cache {
		if cacheMap, ok := cacheData.(map[string]interface{}); ok {
			// 缓存键数量
			if keys, exists := cacheMap["keys"]; exists {
				if keysFloat, ok := keys.(float64); ok {
					ch <- prometheus.MustNewConstMetric(
						c.cacheKeys,
						prometheus.GaugeValue,
						keysFloat,
						socket, cacheName,
					)
				}
			}

			// 缓存命中数
			if hits, exists := cacheMap["hits"]; exists {
				if hitsFloat, ok := hits.(float64); ok {
					ch <- prometheus.MustNewConstMetric(
						c.cacheHits,
						prometheus.CounterValue,
						hitsFloat,
						socket, cacheName,
					)
				}
			}

			// 缓存未命中数
			if misses, exists := cacheMap["misses"]; exists {
				if missesFloat, ok := misses.(float64); ok {
					ch <- prometheus.MustNewConstMetric(
						c.cacheMisses,
						prometheus.CounterValue,
						missesFloat,
						socket, cacheName,
					)
				}
			}
		}
	}
}

// collectLockMetrics 收集锁指标
func (c *Collector) collectLockMetrics(stats *uWSGIStats, socket string, ch chan<- prometheus.Metric) {
	for i, lockData := range stats.Locks {
		if lockMap, ok := lockData.(map[string]interface{}); ok {
			// 遍历锁映射中的每个锁
			for lockName, lockValue := range lockMap {
				if lockFloat, ok := lockValue.(float64); ok {
					ch <- prometheus.MustNewConstMetric(
						c.locksCount,
						prometheus.GaugeValue,
						lockFloat,
						socket, lockName,
					)
				}
			}
		} else {
			// 如果不是map，使用索引作为锁名
			lockName := "lock_" + strconv.Itoa(i)
			if lockFloat, ok := lockData.(float64); ok {
				ch <- prometheus.MustNewConstMetric(
					c.locksCount,
					prometheus.GaugeValue,
					lockFloat,
					socket, lockName,
				)
			}
		}
	}
}

// getSocketType 获取socket类型
func (c *Collector) getSocketType(socket string) string {
	if socketType, exists := c.config.SocketTypes[socket]; exists {
		return socketType
	}

	// 自动检测
	if socket[0] == '/' || (len(socket) > 1 && socket[:2] == "./") {
		return "unix"
	}
	return "tcp"
}

// UpdateConfig 更新配置
func (c *Collector) UpdateConfig(cfg *config.Config) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.config = cfg
}
